<!--  -->
<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <acc-set-card></acc-set-card>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="saveEdit()">保存</el-button>
            </div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
                <el-row>
                    <el-col :sm="20" :md="10">
                        <el-form-item label="凭证号">
                            <el-input v-model="ruleForm.vochNum" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="20" :md="5">
                        <el-form-item prop="orderRuleName" label="单别">
                            <!-- <div @click="showbillDialog('单别')">
                                <el-input v-model="ruleForm.orderNoCode" readonly>
                                    <i slot="suffix" class="el-icon-search"></i>
                                </el-input>
                            </div> -->
                            <el-select
                                v-model="ruleForm.orderRuleName"
                                placeholder="请选择"
                                clearable
                                @focus="getOrderNoList"
                                @change="setOrderNo($event)"
                            >
                                <el-option
                                    :label="item.ruleName"
                                    :value="item.ruleName"
                                    v-for="(item, index) in orderNoList"
                                    :key="index"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :sm="20" :md="5">
                        <el-form-item label="附件数" prop="docNums">
                            <el-input type="number" min="1" v-model="ruleForm.docNums"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :sm="20" :md="5">
                        <el-form-item label="凭证日期">
                            <el-date-picker
                                style="width:99%"
                                v-model="ruleForm.vnDate"
                                align="right"
                                type="date"
                                placeholder="选择日期"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="20" :md="5">
                        <el-form-item label="会计期间" prop="period">
                            <el-select
                                v-model="ruleForm.period"
                                placeholder="请选择"
                                clearable
                                @focus="getPeriodList"
                            >
                                <el-option
                                    :label="item"
                                    :value="item"
                                    v-for="(item, index) in periodList"
                                    :key="index"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="20" :md="10">
                        <el-form-item label="备注">
                            <el-input v-model="ruleForm.remark" ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="margin-top:10px;border:1px solid">
                <div style="margin:10px;">
                    <vxe-toolbar>
                        <template v-slot:buttons>
                            明细列表
                            <vxe-button
                                status="primary"
                                icon="fa fa-plus"
                                @click="insertEvent(-1)"
                            >新增行</vxe-button>
                            <vxe-button status="danger" @click="deleteCheckBoxRow()">删除选中行</vxe-button>
                        </template>
                    </vxe-toolbar>

                    <vxe-table
                        keep-source
                        stripe
                        border
                        show-footer
                        :footer-method="footerMethod"
                        resizable
                        ref="xTable"
                        :data="tableData"
                        :edit-rules="validRules"
                        :edit-config="{trigger: 'click', mode: 'cell'}"
                        @edit-actived="editActivedEvent"
                    >
                        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                        <vxe-table-column type="seq" width="60"></vxe-table-column>
                        <vxe-table-column
                            field="snNo"
                            title="序号"
                            :edit-render="{name: 'input', attrs: {type: 'number'}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="remark"
                            title="摘要说明"
                            :edit-render="{name: '$input', attrs: {type: 'text'}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="subCode"
                            title="科目"
                            :edit-render="{name: '$input', events: {focus: adSubFocusEvent}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="subName"
                            title="科目名称"
                            :edit-render="{name: '$input', attrs: {type: 'text'}, props: {disabled: true}} "
                        ></vxe-table-column>

                            <vxe-table-column
                            field="debitAmt"
                            title="本币借方"
                            :edit-render="{name: '$input', props: { disabled: disabledArr.debitAmtDisabled}}"
                        ></vxe-table-column>
                            <vxe-table-column
                            field="crebitAmt"
                            title="本币贷方"
                            :edit-render="{name: '$input', props: { disabled: disabledArr.crebitAmtDisabled}}"
                        ></vxe-table-column>
                            <vxe-table-column
                            field="debitAmtOc"
                            title="原币借方"
                            :edit-render="{name: '$input', props: {disabled: disabledArr.debitAmtOcDisabled}, events: {input: debitChangeEvent}}"
                        ></vxe-table-column>
                            <vxe-table-column
                            field="crebitAmtOc"
                            title="原币贷方"
                            :edit-render="{name: '$input', props: {disabled: disabledArr.crebitAmtOcDisabled}, events: {input: crebitChangeEvent}}"
                        ></vxe-table-column>
                        <!-- <vxe-table-column
                            field="currId"
                            title="币别"
                            :edit-render="{
                                name: '$select',  
                                options: currList, 
                                optionProps: {value: 'id', label: 'currCode'}, 
                                events: {change: currRateChangeEvent}}"
                        ></vxe-table-column> -->
                        <vxe-table-column
                            field="currCode"
                            title="币别"
                            :edit-render="{name: '$input', props: {readonly: true, disabled: disabledArr.currCodeDisabled}, events: {focus: showCurrDialog}}"
                        ></vxe-table-column>

                        <vxe-table-column
                            field="rate"
                            title="汇率"
                            :edit-render="{name: '$input', props: {disabled: disabledArr.rateDisabled}, events: {input: rateChangeEvent}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="empName"
                            title="人员"
                            :edit-render="{name: '$input',  props: {disabled: disabledArr.empNameDisabled}, events: {focus: showTreeDialog}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="deptName"
                            title="部门"
                            :edit-render="{name: '$select', props: {disabled: disabledArr.deptNameDisabled}, options: departList, optionProps: {value: 'id', label: 'name'}, events: {change: departChangeEvent}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="tranName"
                            title="往来"
                            :edit-render="{name: '$input', props: {disabled: disabledArr.tranNameDisabled}, events: {focus: showCustomerDialog}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="proName"
                            title="项目"
                            :edit-render="{name: '$input', attrs: {type: 'text'}}"
                        ></vxe-table-column>

                        
                    </vxe-table>
                </div>
            </div>
        
        
            <!-- 单别搜索 -->
            <bill-search
                :isShow="showBillSearch"
                :dialogTitle="billSearchDialogTit"
                method="orderNoRuleFindAllPage"
                @edit="billSearchBack"
                @close="closeDialog"
                />
            <!-- 科目搜索 -->
            <tree-search-subject
                :isShow="showSearchSub"
                :dialogTitle="searchDialogTitSub"
                @edit="searchBackSub"
                @close="closeTreeDialogSub"
            ></tree-search-subject>
            <!-- 人员搜索 -->
            <tree-search
                :isShow="showSearch"
                :dialogTitle="searchDialogTit"
                @edit="searchBack"
                @close="closeDialog"
            ></tree-search>
            <!-- 往来人员搜索 -->
            <customer-search
                :isShow="showCustomerSearch"
                :dialogTitle="customerSearchDialogTit"
                method="clientInfoFindAllPageByDTO"
                @edit="customerSearchBack"
                @close="closeDialog"
            ></customer-search>
            <!-- 搜索币别 -->
            <curr-Search
                :isShow="showCurrSearch"
                :dialogTitle="currSearchDialogTit"
                method="currRateFindList"
                @edit="currSearchBack"
                @close="closeDialog"
            ></curr-Search>
            
        </div>
    </div>
</template>

<script>
import appMain from '../../../utils/app_main.js';
import bus from '../../../components/common/bus'
import XEUtils from 'xe-utils';
import app_main from '../../../utils/app_main.js';
var _ = require('lodash');
let moneyReg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{2})$/;
export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            editVisible: false,
            billSearchDialogTit: '', // 单别
            showBillSearch: false, 
            searchDialogTitSub: '', // 科目
            showSearchSub: false,
            searchDialogTit: '', // 人员搜索
            showSearch: false,
            customerSearchDialogTit: '', // 往来人员
            showCustomerSearch: false,
            currSearchDialogTit: '', // 
            showCurrSearch: false,

            isUpdate: false, //是否是更新
            currentRow: '',
            ruleForm: {
                vochNum: '', // 凭证单号:xxxxxxaaaa-200400001,6位公司id+4位单别-年月5位流水
                docNums: '', // 附件张数	默认0可以手工输入	
                orderNoCode: '', // 单别代码	
                orderNoId: '', // 单别id	
                orderRuleName: '',
                period: '', // 会计期间	模拟账套中当前会计期间，可以手工修改	
                remark: '', // 备注	
                vnDate: '', // 凭证日期	系统日期，可以调整
            },
            rules: {
                orderRuleName: { required: true,message: '请选择单别', trigger: 'change'},
                period: { required: true,message: '请选会计期间', trigger: 'change'},
            },
            
            validRules: {
                subCode: [{ required: true, message: '计划日期必须填写' }],
                // points: [
                //     { required: true, message: '计划金额必须填写' },
                //     { pattern: '^(0|[1-9][0-9]*)$', message: '格式不正确' }
                // ],
                subName: [
                    { min: 2, max: 300, message: '长度在 2 到 300 个字符' }
                ]
            },
            tableData: [],
            
            disabledArr: { // 是否可操作 true为不可操作
                debitAmtDisabled: true,
                crebitAmtDisabled: true,
                debitAmtOcDisabled: true,
                crebitAmtOcDisabled: true,
                currCodeDisabled: true,
                rateDisabled: true,
                empNameDisabled: true,
                deptNameDisabled: true,
                tranNameDisabled: true,
            },


            periodList: [], // 会计期间列表
            departList: [], // 部门列表
            orderNoList: [], // 单别列表
            currList: [], // 币别列表
            //新增,在编辑的明细行
            editRow: '',
            canUseCurrList: false, // 能不能点击币别
        };
    },
    methods: {
        // 选择单别
        showbillDialog(tit) {
            this.billSearchDialogTit = tit;
            this.showBillSearch = true;
        },
        // 单别搜索结果返回
        billSearchBack(data) {
            console.log(data.backData, 'billSearchBack');
            this.ruleForm.orderNoCode = data.backData.ruleCode;
            // this.ruleForm.ruleName = data.backData.ruleName;
            this.ruleForm.orderNoId = data.backData.id
            this.showBillSearch = false;
        },
        closeDialog (data) {
            this.showBillSearch = false
        },
        close() {
            this.$emit('close', {
                showDialog: false
            });
        },
        // 从弹窗返回主页面的数据
        saveEdit() {
            let self = this;
            this.$refs["ruleForm"].validate(valid => {
                if (valid) {
                    self.submit();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            }); 
        },

         //初始化table
        resetTableData() {
            const length = this.tableData.length;
            if (length < 10) {
                for (let index = 10; index > length; index--) {
                    let record = {
                        crebitAmt: '', // 本币贷方金额	
                        crebitAmtOc: '', // 原币贷方金额	
                        currFlag: '', // 是否核算外币:0否，1是	
                        currId: '', // 币别	
                        dealFlag: '', // 是否核算来往单位：0否 ，1是	
                        debitAmt: '', // 本币借方金额	
                        debitAmtOc: '', // 原币币借方金额	
                        deptFlag: '', // 是否核算部门：0否，1是	
                        deptId: '', // 部门代码	
                        deptName: '', // 部门名称	
                        subName: '', // 科目名称		
                        drFlag: '', // 借贷方向	1、借 2、贷	
                        empFlag: '', // 是否核算人员:0否，1是	
                        empId: '', // 人员代码	
                        empName: '', // 人员姓名	
                        proFlag: '', // 是否核算项目：0否，1是	
                        proId: '', // 项目id	
                        proName	: '', // 项目名称	
                        rate: '', // 汇率	
                        remark: '', // 摘要	
                        setBookId: '', // 账套号	
                        snNo: '', // 单据项次	1 ~9999 用字符排序有效性	
                        subId: '', // 科目id
                        subCode: '',  // 科目代码
                        tranId: '', // 来往单位代码	
                        tranName: '', // 来往单位名称	
                        vochNum: '', // 凭证单号	xxxxxaaaa-200400001:6位公司id+4位单别-年月5位流水	
                        vochNumDetail: '', // 明细凭证单号	
                    };
                    this.tableData.push(record);
                }
            }
            console.log('resetTableData', this.tableData);
        },
        /**
          * vxe-table  start
          * 
          */
        async insertEvent(row) {
            let length = this.$refs.xTable.tableData.length + 1;
            let record = {
                crebitAmt: '', // 本币贷方金额	
                crebitAmtOc: '', // 原币贷方金额	
                currFlag: '', // 是否核算外币:0否，1是	
                currId: '', // 币别	
                dealFlag: '', // 是否核算来往单位：0否 ，1是	
                debitAmt: '', // 本币借方金额	
                debitAmtOc: '', // 原币币借方金额	
                deptFlag: '', // 是否核算部门：0否，1是	
                deptId: '', // 部门代码	
                deptName: '', // 部门名称	
                subName: '', // 科目名称		
                drFlag: '', // 借贷方向	1、借 2、贷	
                empFlag: '', // 是否核算人员:0否，1是	
                empId: '', // 人员代码	
                empName: '', // 人员姓名	
                proFlag: '', // 是否核算项目：0否，1是	
                proId: '', // 项目id	
                proName	: '', // 项目名称	
                rate: '', // 汇率	
                remark: '', // 摘要	
                setBookId: '', // 账套号	
                snNo: length, // 单据项次	1 ~9999 用字符排序有效性	
                subId: '', // 会计科目代码	
                tranId: '', // 来往单位代码	
                tranName: '', // 来往单位名称	
                vochNum: '', // 凭证单号	xxxxxaaaa-200400001:6位公司id+4位单别-年月5位流水	
                vochNumDetail: '', // 明细凭证单号	
            };
            let { row: newRow } = await this.$refs.xTable.insertAt(record, row);
            //await this.$refs.xTable.setActiveCell(newRow, 'sex');
            this.tableData = this.$refs.xTable.tableData
            console.log('insertEvent', this.tableData);
        },
        //删除选中列
        deleteCheckBoxRow() {
            let selectRecords = this.$refs.xTable.getCheckboxRecords();
            if (selectRecords.length < 1) {
                this.$message({
                    message: '请选择一条数据',
                    type: 'info'
                });
            } else {
                this.$refs.xTable.removeCheckboxRow();
                this.tableData = this.$refs.xTable.tableData;
            }
        },
        //新增/更新考核模板
        async submit() {
            let updateRecords = this.$refs.xTable.tableData;
            let newArr = [];
            // 验证科目返回的数据联动的动态必填
            let errMsgarr = [];
            let errMsg = '';
            let canSubmit = true;
            updateRecords.map((item, index) => {
                let canAdd = false; // 要不要加入newArr
                if (item.currFlag && !item.currId) {
                    errMsg = '第' + (index + 1) + '行币种必填'
                    errMsgarr.push(errMsg)
                }
                if (item.dealFlag && !item.tranId) {
                    errMsg = '第' + (index + 1) + '行往来必填'
                    errMsgarr.push(errMsg)
                }
                if (item.deptFlag && !item.deptId) {
                    errMsg = '第' + (index + 1) + '行部门必填'
                    errMsgarr.push(errMsg)
                }
                if (item.empFlag && !item.empId) {
                    errMsg = '第' + (index + 1) + '行人员必填'
                    errMsgarr.push(errMsg)
                }
                for (let key in item) {
                    if (item[key] && key != '_XID') {
                        canAdd = true
                    }
                }
                if (canAdd){
                    newArr.push(item)
                }
                // 几个金额如果为''的话，转成0
                item.debitAmt = Number(item.debitAmt)
                item.crebitAmt = Number(item.crebitAmt)
                item.debitAmtOc = Number(item.debitAmtOc)
                item.crebitAmtOc = Number(item.crebitAmtOc)
                item.rate = item.rate || 0
            });
            if (errMsgarr.length > 0) {
                this.$message({
                    message: errMsgarr.join(','),
                    type: 'error'
                });
                return;
            }
            console.log(updateRecords, newArr)
            if (updateRecords.length > 0) {
                const errMap = await this.$refs.xTable.validate(newArr).catch(errMap => errMap);
                if (errMap) {
                    //this.$XModal.message({ status: 'error', message: '请按要求完成评测！' });
                    this.$message.warning('请按要求填写！');
                } else {
                    //this.$XModal.message({ status: 'success', message: '校验成功！' });
                    let params = {};
                    params.bkpfInfo = this.ruleForm;
                    params.bkpfInfoList = newArr
                    console.log('updateRecords', newArr);
                    let url = '';
                    if (this.isUpdate) {
                        url = 'bkpfInfoUpdateBkpfInfo';
                    } else {
                        url = 'bkpfInfoAddBkpfInfo';
                    }
                    appMain[url](params)
                        .then(res => {
                            if (res.data.code === 20000) {
                                bus.$emit('close_current_tags')
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });
                    console.log(this.$router);
                }
            } else {
                //this.$XModal.message({ status: 'warning', message: '未选中数据！' });
                this.$message.info('无更新数据');
            }
        },
        //表脚
        footerMethod({ columns, data }) {
            return [
                columns.map((column, columnIndex) => {
                    if (columnIndex === 0) {
                        return '合计';
                    }
                    if (columnIndex === 6) {
                        //console.log('columns', data);
                        let coin = `${XEUtils.sum(data, 'debitAmt')}`;
                        // this.ruleForm.total = coin;
                        return coin + ' 元';
                    }
                    if (columnIndex === 7) {
                        //console.log('columns', data);
                        let coin = `${XEUtils.sum(data, 'crebitAmt')}`;
                        // this.ruleForm.total = coin;
                        return coin + ' 元';
                    }
                    return '-';
                })
            ];
        },
        /**
         * vxe-table end
         */ 
        getPeriodList() {
            appMain
                .accPeriodFindDefaultData()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.periodList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 根据id查找凭证
        bkpfInfoFindById(id) {
            appMain
                .bkpfInfoFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.ruleForm = res.data.data.bkpfInfo;
                        this.tableData = res.data.data.bkpfInfoList;
                        if (res.data.data.expectedPlan) {
                            // let arr = JSON.parse(res.data.data.bkpfInfoList)
                            // if (arr.length > 0) {
                            //     this.tableData.splice(0, arr.length)
                            //     this.tableData = arr.concat(this.tableData)
                            // }
                           
                        }
                    } else {
                        this.$message.error('服务器繁忙，请稍后再试');
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 科目树组件搜索结果返回
        searchBackSub(data) {
            console.log(data.backData, '科目搜索返回');
            this.tableData[this.editRow].subId = data.backData.id;
            this.tableData[this.editRow].subName = data.backData.subName;
            this.tableData[this.editRow].subCode = data.backData.subCode
            this.tableData[this.editRow].currFlag = data.backData.currFlag; // 是否核算外币
            this.tableData[this.editRow].dealFlag = data.backData.dealFlag; // 是否合算往来单位
            this.tableData[this.editRow].deptFlag = data.backData.deptFlag; // 是否核算部门
            this.tableData[this.editRow].empFlag = data.backData.empFlag; // 是否核算人员
            this.tableData[this.editRow].proFlag = data.backData.proFlag; // 是否合算项目
            // 清空币别等信息
            this.tableData[this.editRow].debitAmt = '';
            this.tableData[this.editRow].crebitAmt = '';
            this.tableData[this.editRow].debitAmtOc = '';
            this.tableData[this.editRow].crebitAmtOc = '';
            this.tableData[this.editRow].currId =  '';
            this.tableData[this.editRow].currCode = '';
            this.tableData[this.editRow].rate =  '';
            this.tableData[this.editRow].empName = '';
            this.tableData[this.editRow].empId = '';
            this.tableData[this.editRow].tranName = '';
            this.tableData[this.editRow].tranId = '';
            this.tableData[this.editRow].deptId = '';
            this.tableData[this.editRow].deptName = '';
            

            this.showSearchSub = false;
            
        },
        closeTreeDialogSub(data) {
            this.showSearchSub = data.showDialog;
        },
        adSubFocusEvent({ rowIndex }) {
            console.log('adSubFocusEvent', rowIndex);
            this.editRow = rowIndex;
            this.searchDialogTitSub = '科目';
            this.showSearchSub = true;
        },
        // 选择人员
        showTreeDialog({ rowIndex }) {
            console.log('showTreeDialog');
            this.editRow = rowIndex;
            this.searchDialogTit = '人员';
            this.showSearch = true;
        },
        // 人员组件搜索结果返回
        searchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.tableData[this.editRow].empName = data.backData.name;
            this.tableData[this.editRow].empId = data.backData.id;
            this.showSearch = false;
        },
        // 选择客户
        showCustomerDialog({ rowIndex }) {
            this.editRow = rowIndex;
            this.customerSearchDialogTit = '往来客户';
            this.showCustomerSearch = true;
        },
        // 客户搜索结果返回
        customerSearchBack(data) {
            console.log(data.backData, 'customerSearchBack');
            this.tableData[this.editRow].tranName = data.backData.name;
            this.tableData[this.editRow].tranId = data.backData.id;
            this.showCustomerSearch = false;
        },
        // 选择币别
        showCurrDialog({ rowIndex }) {
            this.editRow = rowIndex;
            // 如果科目下的currflag为false不弹出
            if (!this.tableData[this.editRow].currFlag) {
                return
            }
            this.currSearchDialogTit = '币别';
            this.showCurrSearch = true;
        },
         // 币别组件搜索结果返回
        currSearchBack(data) {
            console.log(data.backData, '科目搜索返回');
            this.tableData[this.editRow].currId =  data.backData.id
            this.tableData[this.editRow].currCode = data.backData.currCode     
            this.tableData[this.editRow].rate =  data.backData.rate;
            // 如果之前有填 原币借方或原币贷方进行下计算
            if (appMain.myIsNaN(Number(this.tableData[this.editRow].debitAmtOc)) && this.tableData[this.editRow].debitAmtOc > 0) {
                this.countLamount(this.tableData[this.editRow].debitAmtOc, data.backData.rate, 'debitAmt');
            } else {
                this.countLamount(this.tableData[this.editRow].crebitAmtOc, data.backData.rate, 'crebitAmt');
            }
            
            
            this.showCurrSearch = false;
            
        },
        closeDialog (data) {
            this.showSearch = false;
            this.showBillSearch = false;
            this.showCustomerSearch = false
            this.showCurrSearch = false
        },
        //获取部门搜索元素
        getDepart() {
            appMain
                .organizationUserList()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.departList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        }, 
        // 原币借方更改操作
        debitChangeEvent ({row,rowIndex,$rowIndex,column,columnIndex,$columnIndex}) {
            console.log(row.debitAmtOc, 'debit')
            this.editRow = rowIndex;
            this.tableData[this.editRow].crebitAmtOc = ''
            this.tableData[this.editRow].crebitAmt = ''
            this.countLamount(row.debitAmtOc, row.rate, 'debitAmt');
        },
        // 原币贷方更改操作
        crebitChangeEvent ({row,rowIndex,$rowIndex,column,columnIndex,$columnIndex}) {
            console.log(row.crebitAmtOc, 'crebit')
            this.editRow = rowIndex;
            this.tableData[this.editRow].debitAmtOc = ''
            this.tableData[this.editRow].debitAmt = ''
            this.countLamount(row.crebitAmtOc, row.rate, 'crebitAmt');

        },
        // 币别选择事件
        currRateChangeEvent ({row,rowIndex,$rowIndex,column,columnIndex,$columnIndex}) {
            console.log(row.currId, ' 币别')
            this.editRow = rowIndex;
            let val = row.currId;
            for (const key in this.currList) {
                if (this.currList[key].id == val) {
                    this.tableData[this.editRow].rate = this.currList[key].rate;
                    // 如果之前有填 原币借方或原币贷方进行下计算
                    if (appMain.myIsNaN(Number(row.debitAmtOc)) && row.debitAmtOc > 0) {
                        this.countLamount(row.debitAmtOc, row.rate, 'debitAmt');
                    } else {
                        this.countLamount(row.crebitAmtOc, row.rate, 'crebitAmt');
                    }
                }
            }
        },
        //  汇率变化事件
        rateChangeEvent ({row,rowIndex,$rowIndex,column,columnIndex,$columnIndex}) {
            console.log(row.rate, '汇率')
            this.editRow = rowIndex;
            if (appMain.myIsNaN(Number(row.debitAmtOc)) && row.debitAmtOc > 0) {
                this.countLamount(row.debitAmtOc, row.rate, 'debitAmt');
            } else {
                this.countLamount(row.crebitAmtOc, row.rate, 'crebitAmt');
            }
        },
        // 部门选择事件
        departChangeEvent ({row,rowIndex,$rowIndex,column,columnIndex,$columnIndex}, field) {
            console.log(this.$refs.xTable.tableData)
            console.log(this.tableData[rowIndex].deptName, 'deptName', field)
            this.editRow = rowIndex;
            let val = row.deptName;
     
            for (const key in this.departList) {
                if (this.departList[key].id == val) {
                    this.tableData[this.editRow].deptId = this.departList[key].id;
                    this.tableData[this.editRow].deptName = this.departList[key].name;
                }
            }
        },
        // 币别列表
        currRateFindList() {
            appMain
                .currRateFindList()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.currList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 单别列表
        getOrderNoList() {
            appMain
                .orderNoRuleFindAll()
                .then(res => {
                    if (res.data.code === 20000) {
                        this.orderNoList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        setOrderNo (e) {
            console.log(e);
            let val = e;
            for (const key in this.orderNoList) {
                if (this.orderNoList[key].ruleName == val) {
                    this.ruleForm.orderNoCode = this.orderNoList[key].ruleCode;
                    this.ruleForm.orderRuleName = this.orderNoList[key].ruleName;
                    this.ruleForm.orderNoId =this.orderNoList[key].id
                }
            }
        },
        // 计算 汇率*金额
        countLamount(amount, currRate, itemName) {
            // 没有汇率信息， 不计算
            if (!currRate) {
                return
            }
            let params = {
                amount: amount,
                currRate: currRate
            };
            appMain
                .countLamount(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.tableData[this.editRow][itemName] =  res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
         // 获取当前会计期间
        accPeriodDefaultData () {
            let d = new Date();
            let date_ = d.getFullYear() + '-' + appMain.formatZero(d.getMonth() + 1) + '-' + appMain.formatZero(d.getDate());
            appMain
                .accPeriodDefaultData({}, date_ )
                .then(res => {
                    if (res.data.code === 20000) {
                        this.ruleForm.period = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 设置只有选择科目后，后面的选项才能让它填
        editActivedEvent ({ rowIndex, row }) {
            console.log(row.subId, row.currFlag, 'Disabled ', !row.subId || !row.deptFlag, this.disabledArr)
            this.disabledArr.debitAmtDisabled = !row.subId || row.currFlag == 1
            this.disabledArr.crebitAmtDisabled = !row.subId || row.currFlag == 1
            this.disabledArr.debitAmtOcDisabled = !row.subId || !row.currFlag == 1
            this.disabledArr.crebitAmtOcDisabled = !row.subId || !row.currFlag == 1
            this.disabledArr.currCodeDisabled = !row.subId || !row.currFlag == 1
            this.disabledArr.rateDisabled = !row.subId || !row.currFlag == 1
            this.disabledArr.empNameDisabled = !row.subId || !row.empFlag == 1
            this.disabledArr.deptNameDisabled = !row.subId || !row.deptFlag == 1
            this.disabledArr.tranNameDisabled = !row.subId || !row.dealFlag == 1
        }
    },
    watch: {
    },
    computed: {
        aNum() {
            return 123;
        }
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 160;
        this.pageTitle = this.$router.currentRoute.meta.title;
    },
    created() {
        //如果有id过来就是修改的
        if (this.$route.query.id) {
            let id = this.$route.query.id;
            //是更新操作
            this.isUpdate = true;
            this.ruleForm.vochNum = id
            //通过id查询对应离职信息
            this.bkpfInfoFindById(id);
        } else {
            //新增操作
            this.isUpdate = false;
            this.flag = true;
            // this.resetTableData();
        }

        this.getPeriodList();
        this.getDepart();
        this.currRateFindList();
        this.accPeriodDefaultData()
    }
};
</script>

<style lang="css" scoped>
.container {
    padding-bottom: 50px;
}
.handle-box {
    padding: 5px 50px;
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}
.table-form-box{
    padding-bottom: 100px;
}
.table-form-box table {
    background-color: #666;
}
.table-form-box .h3 {
    font-size: 22px;
    text-align: center;
    font-weight: normal;
    padding: 20px 0;
}
.table-form-box table .tr-title td {
    font-size: 14px;
    line-height: 40px;
}
.table-form-box table td,
.table-form-box table th {
    background-color: #fff;
    padding: 4px;
    min-height: 40px;
    font-size: 12px;
}
.color-ff2200 {
    color: #ff2200;
}

</style>